<script setup>
import { ref, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import logo from '../assets/logo.svg'
import { House, Notebook, User, Tickets, Setting, DataAnalysis, Edit, Calendar, OfficeBuilding, Document, Fold, Expand, Collection } from '@element-plus/icons-vue'
import { ElMessageBox, ElMessage } from 'element-plus'

const router = useRouter()
const route = useRoute()

const user = ref(JSON.parse(localStorage.getItem('user') || '{}'))
const avatarUrl = computed(() => {
  const img = user.value?.image
  if (typeof img === 'string' && img.trim()) return img.replace(/`/g, '').trim()
  return logo
})

async function onLogout() {
  try {
    await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
      type: 'warning',
      confirmButtonText: '退出登录',
      cancelButtonText: '取消',
      autofocus: false,
    })
    localStorage.removeItem('token')
    localStorage.removeItem('user')
    ElMessage.success('已退出登录')
    window.dispatchEvent(new CustomEvent('auth:unauthorized'))
  } catch (e) {
    // 用户点击了取消，无需处理
  }
}

function onSelect(index) {
  router.push(index)
}

const collapsed = ref(false)
const sidebarWidth = computed(() => (collapsed.value ? 64 : 220))
function toggleCollapse() { collapsed.value = !collapsed.value }
</script>

<template>
  <div class="layout">
    <header class="header">
      <div class="brand">
        <img src="/favicon.ico" class="brand-logo" /> QK轻客管家
        <el-button class="collapse-btn" text @click="toggleCollapse">
          <el-icon><Fold v-if="!collapsed" /><Expand v-else /></el-icon>
        </el-button>
      </div>
      <div class="user">
        <img :src="avatarUrl" class="avatar" />
        <span class="name">{{ user.name || user.username || '未登录' }}</span>
        <el-button type="danger" size="small" plain @click="onLogout">退出登录</el-button>
      </div>
    </header>
    <div class="content" :style="{ gridTemplateColumns: `${sidebarWidth}px 1fr` }">
      <aside class="sidebar" :style="{ width: `${sidebarWidth}px` }">
        <div class="sidebar-panel">
          <el-menu
            :default-active="route.path"
            :default-openeds="['grp-leads','grp-opps','grp-resources','grp-system']"
            :collapse="collapsed"
            router
            @select="onSelect"
            class="menu"
          >
            <!-- 首页 -->
            <el-menu-item index="/home" class="menu-dark">
              <el-icon><House /></el-icon>
              <span>首页</span>
            </el-menu-item>

            <!-- 线索管理 -->
            <el-sub-menu index="grp-leads" class="menu-dark">
              <template #title>
                <el-icon><Tickets /></el-icon>
                <span>线索管理</span>
              </template>
              <el-menu-item index="/leads/list">
                <el-icon><Tickets /></el-icon>
                <span>线索列表</span>
              </el-menu-item>
              <el-menu-item index="/leads/pool">
                <el-icon><Tickets /></el-icon>
                <span>线索池</span>
              </el-menu-item>
            </el-sub-menu>

            <!-- 商机管理 -->
            <el-sub-menu index="grp-opps" class="menu-dark">
              <template #title>
                <el-icon><DataAnalysis /></el-icon>
                <span>商机管理</span>
              </template>
              <el-menu-item index="/opps/list">
                <el-icon><DataAnalysis /></el-icon>
                <span>商机列表</span>
              </el-menu-item>
              <el-menu-item index="/opps/pool">
                <el-icon><DataAnalysis /></el-icon>
                <span>公海池</span>
              </el-menu-item>
            </el-sub-menu>

            <!-- 客户管理（单项） -->
            <el-menu-item index="/customers" class="menu-dark">
              <el-icon><User /></el-icon>
              <span>客户管理</span>
            </el-menu-item>

            <!-- 资源管理 -->
            <el-sub-menu index="grp-resources" class="menu-dark">
              <template #title>
                <el-icon><Collection /></el-icon>
                <span>资源管理</span>
              </template>
              <el-menu-item index="/courses">
                <el-icon><Notebook /></el-icon>
                <span>课程管理</span>
              </el-menu-item>
              <el-menu-item index="/activities">
                <el-icon><Calendar /></el-icon>
                <span>活动管理</span>
              </el-menu-item>
            </el-sub-menu>

            <!-- 系统管理 -->
            <el-sub-menu index="grp-system" class="menu-dark">
              <template #title>
                <el-icon><Setting /></el-icon>
                <span>系统管理</span>
              </template>
              <el-menu-item index="/system/departments">
                <el-icon><OfficeBuilding /></el-icon>
                <span>部门管理</span>
              </el-menu-item>
              <el-menu-item index="/system/roles">
                <el-icon><Setting /></el-icon>
                <span>角色管理</span>
              </el-menu-item>
              <el-menu-item index="/system/users">
                <el-icon><User /></el-icon>
                <span>用户管理</span>
              </el-menu-item>
              <el-menu-item index="/system/logs">
                <el-icon><Document /></el-icon>
                <span>系统日志</span>
              </el-menu-item>
            </el-sub-menu>
          </el-menu>
        </div>
      </aside>
      <main class="main">
        <router-view />
      </main>
    </div>
  </div>
</template>

<style scoped>
.layout { min-height: 100vh; display: grid; grid-template-rows: 56px 1fr; }
.header { display: flex; align-items: center; justify-content: space-between; padding: 0 16px; background: linear-gradient(90deg,#5cc0ff,#1677ff); color: #fff; }
.brand { display: flex; align-items: center; gap: 8px; font-weight: 800; letter-spacing: 1px; }
.brand-logo { width: 24px; height: 24px; }
.user { display: flex; align-items: center; gap: 10px; }
.avatar { width: 30px; height: 30px; border-radius: 50%; background: #fff; }
.content { display: grid; grid-template-columns: 220px 1fr; }
.sidebar { background: transparent; border-right: none; padding: 8px; }
.sidebar-panel { height: calc(100vh - 56px - 16px); background: #fff; border-radius: 12px; box-shadow: 0 6px 20px rgba(0,0,0,0.08); overflow: hidden; }
.menu { height: 100%; border-right: none; padding: 8px 0; }
.menu :deep(.el-sub-menu__title) { font-weight: 600; color: #34495e; }
.menu :deep(.el-menu-item) { height: 40px; line-height: 40px; }
.menu :deep(.el-menu-item .el-icon), .menu :deep(.el-sub-menu__title .el-icon) { margin-right: 8px; }

/* 深色标识（仅用于顶层菜单项与分组标题） */
/* 调整为浅蓝色（Material Blue 200/300），提升区分度同时保持清爽视觉 */
.menu :deep(.menu-dark.el-menu-item) { background-color: #BBDEFB; color: #0d47a1; border-radius: 8px; margin: 4px 8px; }
.menu :deep(.menu-dark.el-menu-item.is-active) { background-color: #90CAF9; color: #0d47a1; }
.menu :deep(.menu-dark > .el-sub-menu__title) { background-color: #BBDEFB; color: #0d47a1; border-radius: 8px; margin: 4px 8px; }
.menu :deep(.menu-dark.is-opened > .el-sub-menu__title) { background-color: #90CAF9; color: #0d47a1; }
.menu :deep(.menu-dark > .el-sub-menu__title .el-icon) { color: #0d47a1; }

/* 普通菜单项的高亮保持原样 */
.menu :deep(.el-menu-item.is-active) { background-color: #e8f3ff; color: #1677ff; }
.collapse-btn { color: #fff; margin-left: 8px; }
.main { background: #f7f7f8; padding: 16px; }
</style>